package com.rongke.redis;

import com.google.gson.Gson;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * Created by bilibili on 2017/8/14.
 */
@Component
public class CacheUtilImpl implements CacheUtil {


    @Autowired
    private StringRedisTemplate redisTemplate;//redis操作模板


    public void put(String key, String value) {
        if (key==null || "".equals(key)) {
            return;
        }
        redisTemplate.opsForHash().put(key, key, value);

    }


    public void put(String key, Object value) {
        if (key==null || "".equals(key)) {
            return;
        }
        redisTemplate.opsForHash().put(key, key, new Gson().toJson(value));

    }



    public <T> T get(String key, Class<T> className) {
        Object obj = redisTemplate.opsForHash().get(key, key);
        if(obj == null){
            return null;
        }
        return new Gson().fromJson(""+obj, className);
    }


    public String get(String key) {
        Object obj = redisTemplate.opsForHash().get(key, key);
        if(obj == null){
            return null;
        }else{
            return String.valueOf(obj);
        }
    }

    public void sendString(String key,Integer time) {
        try {
            redisTemplate.boundValueOps(key).set(key, time, TimeUnit.SECONDS);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public String getString(String key) {
        String temp=null;
        try {
             temp = redisTemplate.boundValueOps(key).get();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return temp;
    }


    public  boolean hasKey(String key){

        return  redisTemplate.hasKey(key);
    }

     public  void  delkey(String key){

         redisTemplate.delete(key);

     }


}
